package com.arpa.wms.service.impl;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.CommonUtil;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.wms.cache.BatchRuleCache;
import com.arpa.wms.cache.GoodsCache;
import com.arpa.wms.cache.LocationCache;
import com.arpa.wms.cache.UnitCache;
import com.arpa.wms.domain.dto.PutawayItemDTO;
import com.arpa.wms.domain.entity.Location;
import com.arpa.wms.domain.entity.PutawayItem;
import com.arpa.wms.domain.entity.WmsTaskItem;
import com.arpa.wms.domain.enums.PutawayItemStatusEnum;
import com.arpa.wms.domain.vo.PutawayItemVO;
import com.arpa.wms.domain.vo.PutawayItemWithRegisterVO;
import com.arpa.wms.mapper.PutawayItemMapper;
import com.arpa.wms.service.IGoodsPnService;
import com.arpa.wms.service.IPutawayItemService;
import com.arpa.wms.service.IWmsTaskItemService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.arpa.wms.domain.consts.CommonConst.LOT_NUMBER;
import static com.arpa.wms.domain.consts.NumConst.NUM_ONE;
import static com.arpa.wms.domain.consts.NumConst.NUM_ZERO;

/**
 * <p>
 * 上架明细 服务实现类
 * </p>
 *
 * @author LEO
 * @since 2020-08-04
 */
@Service
public class PutawayItemServiceImpl extends ServiceImpl<PutawayItemMapper, PutawayItem> implements IPutawayItemService {

    @Autowired
    private UnitCache unitCache;

    @Autowired
    private LocationCache locationCache;
    @Autowired
    @Lazy
    private IWmsTaskItemService wmsTaskItemService;
    @Autowired
    private GoodsCache goodsCache;
    @Autowired
    private BatchRuleCache batchRuleCache;

    @Autowired
    private IGoodsPnService goodsPnService;
    /**
     * 保存
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor={Exception.class})
    public boolean save(PutawayItem entity) {
        if(StringUtils.isBlank(entity.getCode())){
            entity.setCode(IdUtil.simpleUUID());
        }
        if(StringUtils.isBlank(entity.getCreatedBy())){
            entity.setCreatedBy(UserUtil.getCode());
        }
        return super.save(entity);
    }

    /**
     * 根据code更新实体
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor={Exception.class})
    public int updateByCode(PutawayItem entity) {
        if(StringUtils.isBlank(entity.getModifiedBy())){
            entity.setModifiedBy(UserUtil.getCode());
        }
        return baseMapper.update(entity,new QueryWrapper<PutawayItem>().lambda().eq(PutawayItem::getCode,entity.getCode()));
    }

    /**
     * 查询列表
     * @param putawayItemDTO
     * @return
     */
    @Override
    public List<PutawayItemVO> queryList(PutawayItemDTO putawayItemDTO){
        //排序字段名需要驼峰转数据库下划线类型字段名
        if(StringUtils.isNotEmpty(putawayItemDTO.getSortField())){
            putawayItemDTO.setSortField(CommonUtil.camel2Underline(putawayItemDTO.getSortField()));
        }
        List<PutawayItemVO> putawayItemVOList = baseMapper.queryList(putawayItemDTO);
        return putawayItemVOList;
    }

    /**
     * 查询合计,包含总数
     * @param putawayItemDTO
     * @return
     */
    @Override
    public PutawayItemVO queryListSum(PutawayItemDTO putawayItemDTO){
        PutawayItemVO putawayItemVO = baseMapper.queryListSum(putawayItemDTO);
        return putawayItemVO;
    }

    /**
     * 根据code字符串获取上架单详情列表
     * @param codes
     * @return
     */
    @Override
    public List<PutawayItemVO> queryListByCodes(List<String> codes,String groupCode) {
        return this.baseMapper.getListByCodes(codes,groupCode);
    }

    @Override
    public List<PutawayItem> queryAllList(LambdaQueryWrapper<PutawayItem> eq) {
        return this.baseMapper.selectList(eq);
    }

    @Override
    public List<PutawayItemWithRegisterVO> queryItemWithRegisterList(PutawayItemDTO putawayItemDTO) {
        putawayItemDTO.setGroupCode(UserUtil.getBranchCode());
        List<PutawayItemWithRegisterVO> putawayItemWithRegisterVOS = this.baseMapper.queryItemWithRegisterList(putawayItemDTO);
        // 翻译
        putawayItemWithRegisterVOS.stream().forEach(e->{
            Location location = locationCache.getObj(e.getRecommendLocation());
            if (null != location) {
                e.setRecommendLocationName(location.getSerialNumber());
                e.setRecommendSpaceCode(location.getSpaceCode());
            }
            e.setLocationName(locationCache.translate(e.getLocation()));
        });
        return putawayItemWithRegisterVOS;
    }

    /**
     * @param code           :
     * @param registerStatus :
     * @description 更新上架明细的已上架数量
     * @author xuyang
     * @date 2020/10/30 16:31
     **/
    @Override
    public int updateRegisterQuantity(String code, String registerStatus) {
        return this.baseMapper.updateRegisterQuantity(code, registerStatus,UserUtil.getBranchCode());
    }

    @Override
    public Result putawayInfo(PutawayItemDTO putawayItemDTO) {
        String groupCode = UserUtil.getBranchCode();
        //通过任务号获取任务明细
        List<WmsTaskItem> wmsTaskItemList = wmsTaskItemService.list(Wrappers.lambdaQuery(WmsTaskItem.class)
                .select(WmsTaskItem::getTaskCode,WmsTaskItem::getSourceCode)
                .eq(WmsTaskItem::getGroupCode,groupCode)
                .eq(WmsTaskItem::getTaskCode, putawayItemDTO.getTaskCode()));
        //获取上架明细标识
        List<String> putawayItemCodes = wmsTaskItemList.stream().map(WmsTaskItem::getSourceCode).collect(Collectors.toList());
        List<PutawayItemVO> putawayItemVOList = null;
        //获取上架明细信息
        List<PutawayItemVO> tempList = queryListByCodes(putawayItemCodes,groupCode);
        if(putawayItemDTO.getContainer().equals(NUM_ZERO)) {


            String shipmentCode = baseMapper.getShipmentCodeByTaskCode(putawayItemDTO.getTaskCode());
            if (  StrUtil.isNotBlank(shipmentCode)) {
                String goodsCode =  goodsPnService.getGoodsCode(shipmentCode, putawayItemDTO.getGoodsBarCode());
                if(StrUtil.isNotBlank(goodsCode)) {
                    putawayItemVOList = tempList.stream().filter(item -> item.getGoodsCode().equals(goodsCode)
                            && (StrUtil.containsAny(item.getStatus(), PutawayItemStatusEnum.WAITING.getValue(), PutawayItemStatusEnum.PUTAWAYING.getValue()))).collect(Collectors.toList());
                }
            }


        } else {
            //获取上架明细信息
            putawayItemVOList = tempList.stream()
                    .filter(item -> StrUtil.containsAny(item.getStatus(), PutawayItemStatusEnum.WAITING.getValue(), PutawayItemStatusEnum.PUTAWAYING.getValue()))
                    .collect(Collectors.toList());
        }
        if(IterUtil.isEmpty(putawayItemVOList)) {
            throw new ServiceException("上架明细：条码为" + putawayItemDTO.getGoodsBarCode() + "的商品不存在！");
        }
        putawayItemVOList.forEach(e->{
            e.setTaskCode(wmsTaskItemList.get(0).getTaskCode());
            e.setRecommendLocationName(locationCache.translate(e.getRecommendLocation()));
        });
        // 添加批次规则
        if (IterUtil.isNotEmpty(putawayItemVOList)) {
            putawayItemVOList.forEach(item -> {
                Map<String, Object> goodsCacheMap = goodsCache.get(item.getGoodsCode());
                Map<String, Object> batchRuleMap = batchRuleCache.get((String) goodsCacheMap.get(LOT_NUMBER));
                item.setBatchRule(batchRuleMap);
            });
        }
        // 如果有多条
       /* if(putawayItemVOList.size() > NUM_ONE) {
            if(StrUtil.isBlank(putawayItemDTO.getCode())) {
                return Result.ok().data(putawayItemVOList);
            }

//            List<PutawayItemVO> collect = putawayItemVOList.stream().filter(item -> item.getCode().equals(putawayItemDTO.getCode())).collect(Collectors.toList());
//            return Result.ok().data(collect);
        }*/

        return Result.ok().data(putawayItemVOList);
    }


}
